package com.nxcy.com.nxcy.servlet;


import com.google.gson.Gson;
import com.mongodb.client.*;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;

@WebServlet(urlPatterns = {"/student/delete.do"})
public class DeleteStudentServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String url = "mongodb://g08:abc%408@mongo.zhledu.cn:27017/g08";
        MongoClient client = MongoClients.create(url);
        MongoIterable<String> names = client.listDatabaseNames();
        MongoDatabase g08 = client.getDatabase("g08");
        MongoCollection<Document> collection = g08.getCollection("student");
        String sno = request.getParameter("snos");
        String snos[] = new String[]{};
        if (sno != null && sno.length() != 0) {
            snos = sno.split(",");
        }


        Document doc = new Document();
        doc.append("sno", new Document("$in", Arrays.asList(snos)));
        DeleteResult deleteResult = collection.deleteMany(doc);
        Map<String, Object> result = new HashMap();
        if (deleteResult.getDeletedCount() > 0) {
            result.put("code", 0);
        } else {
            result.put("code", -1);
        }

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        Gson gson = new Gson();
        response.getWriter().write(gson.toJson(result));
    }
}
